<template>
  <div class="text-generation-container">
    <div class="btn-animate btn-animate__surround" @click="goToHome">
      <span>🏠点击返回主页面</span>
    </div>
    
    <div class="header">
      <h1>📝 AI文本生成</h1>
      <p class="subtitle">基于先进AI模型的智能文本创作助手</p>
    </div>

    <div class="content-wrapper">
      <!-- 输入区域 -->
      <div class="input-section">
        <div class="section-title">
          <span class="icon">🎯</span>
          <h3>输入提示</h3>
        </div>
        
        <div class="input-group">
          <label for="prompt">请输入您的提示文本：</label>
          <textarea
            id="prompt"
            v-model="prompt"
            placeholder="例如：今天天气很好，我打算去..."
            :maxlength="500"
            class="prompt-textarea"
            @input="handleInput"
          ></textarea>
          <div class="char-count">{{ prompt.length }}/500</div>
        </div>

        <div class="parameters-grid">
          <div class="param-item">
            <label for="maxLength">最大长度：</label>
            <div class="slider-container">
              <input
                id="maxLength"
                v-model.number="maxLength"
                type="range"
                min="50"
                max="500"
                step="10"
                class="slider"
              >
              <span class="value">{{ maxLength }}</span>
            </div>
          </div>

          <div class="param-item">
            <label for="minLength">最小长度：</label>
            <div class="slider-container">
              <input
                id="minLength"
                v-model.number="minLength"
                type="range"
                min="20"
                :max="maxLength - 10"
                step="5"
                class="slider"
              >
              <span class="value">{{ minLength }}</span>
            </div>
          </div>

          <div class="param-item">
            <label for="temperature">创造力：</label>
            <div class="slider-container">
              <input
                id="temperature"
                v-model.number="temperature"
                type="range"
                min="0.1"
                max="1.0"
                step="0.1"
                class="slider"
              >
              <span class="value">{{ temperature }}</span>
              <div class="temperature-hint">
                <span v-if="temperature < 0.4">保守</span>
                <span v-else-if="temperature < 0.7">平衡</span>
                <span v-else>创意</span>
              </div>
            </div>
          </div>
        </div>

        <div class="action-buttons">
          <button
            class="generate-btn"
            :class="{ 'loading': isLoading }"
            :disabled="!canGenerate"
            @click="generateText"
          >
            <span v-if="!isLoading">✨ 开始生成</span>
            <span v-else>
              <div class="spinner"></div>
              生成中...
            </span>
          </button>
          <button
            class="clear-btn"
            @click="clearAll"
            :disabled="isLoading"
          >
            🗑️ 清空内容
          </button>
        </div>
      </div>

      <!-- 结果区域 -->
      <div class="result-section" v-if="generatedText || error">
        <div class="section-title">
          <span class="icon">🎨</span>
          <h3>生成结果</h3>
          <button
            v-if="generatedText"
            class="copy-btn"
            @click="copyToClipboard"
          >
            📋 复制文本
          </button>
        </div>

        <div v-if="error" class="error-message">
          <div class="error-icon">⚠️</div>
          <div class="error-content">
            <h4>生成失败</h4>
            <p>{{ error }}</p>
          </div>
        </div>

        <div v-else-if="generatedText" class="result-content">
          <div class="result-stats">
            <div class="stat-item">
              <span class="stat-label">生成字数：</span>
              <span class="stat-value">{{ generatedText.length }} 字</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">耗时：</span>
              <span class="stat-value">{{ generationTime }} 秒</span>
            </div>
          </div>
          
          <div class="result-text">
            <div class="text-label">生成的文本：</div>
            <div class="generated-text" v-html="formatText(generatedText)"></div>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div class="history-section" v-if="history.length > 0">
        <div class="section-title">
          <span class="icon">📚</span>
          <h3>历史记录</h3>
          <button class="clear-history-btn" @click="clearHistory">清空历史</button>
        </div>
        
        <div class="history-list">
          <div
            v-for="(item, index) in history.slice(-5).reverse()"
            :key="index"
            class="history-item"
          >
            <div class="history-prompt">
              <strong>提示：</strong>{{ item.prompt }}
            </div>
            <div class="history-result">
              {{ item.result.substring(0, 100) }}...
            </div>
            <div class="history-meta">
              <span>{{ item.timestamp }}</span>
              <button @click="reusePrompt(item.prompt)">重用</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 返回首页函数
const goToHome = () => {
  router.push('/')
}

// 状态管理
const prompt = ref('')
const maxLength = ref(200)
const minLength = ref(50)
const temperature = ref(0.7)
const isLoading = ref(false)
const generatedText = ref('')
const error = ref('')
const generationTime = ref(0)
const history = ref<Array<{ prompt: string; result: string; timestamp: string }>>([])

// 计算属性
const canGenerate = computed(() => {
  return prompt.value.trim().length > 0 && !isLoading.value
})

// 方法
const handleInput = () => {
  error.value = ''
}

const generateText = async () => {
  if (!canGenerate.value) return

  isLoading.value = true
  error.value = ''
  generatedText.value = ''
  
  const startTime = Date.now()

  try {
    const response = await fetch('http://localhost:5000/api/text-generation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: prompt.value.trim(),
        max_length: maxLength.value,
        min_length: minLength.value,
        temperature: temperature.value
      })
    })

    const data = await response.json()

    if (data.success) {
      generatedText.value = data.generated_text
      generationTime.value = Number(((Date.now() - startTime) / 1000).toFixed(1))
      
      // 添加到历史记录
      history.value.push({
        prompt: prompt.value,
        result: data.generated_text,
        timestamp: new Date().toLocaleString('zh-CN')
      })
      
      ElMessage.success('文本生成成功！')
    } else {
      error.value = data.error || '生成失败，请重试'
      ElMessage.error(error.value)
    }
  } catch (err) {
    error.value = '网络连接失败，请检查服务是否启动'
    ElMessage.error(error.value)
  } finally {
    isLoading.value = false
  }
}

const clearAll = () => {
  prompt.value = ''
  generatedText.value = ''
  error.value = ''
  maxLength.value = 200
  minLength.value = 50
  temperature.value = 0.7
}

const clearHistory = () => {
  history.value = []
  ElMessage.success('历史记录已清空')
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(generatedText.value)
    ElMessage.success('文本已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败，请手动选择复制')
  }
}

const reusePrompt = (oldPrompt: string) => {
  prompt.value = oldPrompt
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const formatText = (text: string) => {
  return text.replace(/\n/g, '<br>')
}

// 监听参数变化
import { watch } from 'vue'
watch([maxLength, minLength], () => {
  if (minLength.value >= maxLength.value) {
    minLength.value = maxLength.value - 10
  }
})
</script>

<style scoped>
@import '../assets/TextGeneration.css'
</style>
